
global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/bvd_year_lists.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {


/* This do-file creates empty firm-year lists for all different weight types to be run AFTER dep_vars.do*/


*first tfacit1
*merge depvars and weights files, keep only the firm identifiers and save the list
foreach ww in from1970 from1970_totlsw f1970t1989 from1970_GDP0 from1970_GDP1 10yr {
	use ${dataset_dir}/dep_vars/bvd_year_depvars_list.dta, clear
	mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_`ww'_1995_orbis2017_tfacit1.dta, ukeep(BvD) unmatched(none)
	drop _m
	save ${dataset_dir}/dep_vars/bvd_year_list_`ww'_tfacit1.dta, replace
}

clear

*collect all weights files; keep all unique firms
foreach ww in from1970 from1970_totlsw f1970t1989 from1970_GDP0 from1970_GDP1 10yr {
	append using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_`ww'_1995_orbis2017_tfacit1.dta
}
tempfile any_tfacit1
save `any_tfacit1'
keep BvD
duplicates drop

*merge the depvars with those unique firms use literally anywhere
mmerge BvD using ${dataset_dir}/dep_vars/bvd_year_depvars_list.dta, unmatched(none)
drop _m
save ${dataset_dir}/dep_vars/bvd_year_list_any_tfacit1.dta, replace


* Now Inventorweighted, merge with depvars and save the list
use ${dataset_dir}/dep_vars/bvd_year_depvars_list.dta, clear
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_iw.dta, ukeep(BvD) unmatched(none)
drop _m
save ${dataset_dir}/dep_vars/bvd_year_list_from1970_iw.dta, replace

*add the any list, get a complete set of firms used anywhere for any purpose (depvars or spillovers for any window)
use  `any_tfacit1', clear
append using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_iw.dta
keep BvD
duplicates drop
mmerge BvD using ${dataset_dir}/dep_vars/bvd_year_depvars_list.dta, unmatched(none)
drop _m
save ${dataset_dir}/dep_vars/bvd_year_list_any_any.dta, replace

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat